<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="发生地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入发生地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="涉及金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入涉及金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
                        v-model="queryParams.startTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="信用分影响" prop="creditImpact">
        <el-input
          v-model="queryParams.creditImpact"
          placeholder="请输入信用分影响"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['creditlife:behavior']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="behaviorList" @selection-change="handleSelectionChange">
      <el-table-column label="数据ID" align="center" prop="id" />
      <el-table-column label="行为类型" align="center" prop="behaviorType" />
      <el-table-column label="发生地点" align="center" prop="location" />
      <el-table-column label="涉及金额" align="center" prop="amount" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态:进行中/已完成/已逾期" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '进行中'"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['creditlife:behavior']"
          ><i class="el-icon-goods"></i>去结算</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 结算费用对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="behaviorRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="待缴费：" prop="amount">
          <el-tag v-if="form.amount">{{ form.amount }}元</el-tag>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listBehavior, getBehavior, delBehavior, addBehavior, updateBehavior } from "@/api/creditlife/behavior.js"

export default {
  name: "Behavior",
  data() {
    return {
      behaviorList: [],
      open: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        serviceType: null,
        behaviorType: null,
        location: null,
        amount: null,
        startTime: null,
        endTime: null,
        status: null,
        creditImpact: null
      },
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        serviceType: [
          { required: true, message: "服务类型ID不能为空", trigger: "change" }
        ],
        behaviorType: [
          { required: true, message: "行为类型(图书借阅/便捷泊车等)不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态:进行中/已完成/已逾期不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    /** 查询信用生活行为记录列表 */
    getList() {
      this.loading = true
      listBehavior(this.queryParams).then(response => {
        this.behaviorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        serviceType: null,
        behaviorType: null,
        location: null,
        amount: null,
        startTime: null,
        endTime: null,
        status: null,
        creditImpact: null
      };

      // 只在表单引用存在时重置
      if (this.$refs.behaviorRef) {
        this.$nextTick(() => {
          this.$refs.behaviorRef.resetFields();
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryRef.resetFields()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加信用生活行为记录"
    },
    handleUpdate(row) {
      this.reset();
      const _id = row.id || this.ids;
      getBehavior(_id).then(response => {
        this.form = response.data;
        this.open = true;  // 先打开对话框
        this.title = "结算费用";
        // 确保表单引用存在后再设置数据
        this.$nextTick(() => {
          if (this.$refs.behaviorRef) {
            this.$refs.behaviorRef.clearValidate();
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["behaviorRef"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBehavior(this.form).then(response => {
              this.$modal.msgSuccess("操作成功")
              this.open = false
              this.getList()
            })
          } else {
            addBehavior(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const _ids = row.id || this.ids
      this.$modal.confirm('是否确认删除信用生活行为记录编号为"' + _ids + '"的数据项？').then(() => {
        return delBehavior(_ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('creditlife/behavior/export', {
        ...this.queryParams
      }, `behavior_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
